package cn.zjk.springframework.beans.factory.support;

import cn.zjk.springframework.beans.BeansException;
import cn.zjk.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JDK实例化
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instance(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args){
        Class clazz = beanDefinition.getBeanClass();
        try {
            if(null != constructor){
                /*
                有参构造函数
                把入参信息传递给newInstance进行实例化
                 */
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            }else{
                //无参构造函数
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new BeansException("Failed to instance ["+clazz.getName()+"]");
        }
    }
}
